package game.engine;

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


/**
 * Parses Xml to get the sprite data from the file.
 * 
 * @author mah75
 * 
 */
public class XmlParser extends LevelParser {

    private File myXmlFile;
    private Document myXmlDocument;

    /**
     * Initiates the process for parsing an Xml file.
     *
     * @param file The Xml file that will be parsed.
     */
    public XmlParser (File file) {
        super(file);
        myXmlFile = file;
        makeDocument();
    }

    /**
     * Enables parsing of the Xml file.  myXmlDocument is then the basis
     * for the rest of the parsing.
     */
    private void makeDocument () {
        try {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                    .newInstance();
            myXmlDocument = dbFactory.newDocumentBuilder().parse(myXmlFile);
        }
        catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        catch (SAXException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 
     * @return The root tag in the XML document
     */
    @Override
    public Element getRootElement () {
        makeDocument();
        return myXmlDocument.getDocumentElement();
    }

    /**
     * 
     * @param element The tag that contains a section of XML to look through
     * @param name The string name of the desired element
     * @return A node list containing the desired element and its
     *         associated section of XML
     */
    @Override
    public NodeList getElementsByName (Element element, String name) {
        return element.getElementsByTagName(name);
    }

    /**
     * 
     * @param element The tag that contains a section of XML to look through
     * @param getString The string name of the element containing desired text
     * @return The text contained in these desired tags
     */
    @Override
    public String getTextContent (Element element, String getString) {
        NodeList list = element.getElementsByTagName(getString);
        return list.item(0).getTextContent();
    }

    /**
     * Used to test reflection of methods
     *
     * @param s String to be printed
     */
    public void printString (String s) {
        System.out.println(s);
    }

    @Override
    public boolean isValid () {
        return !(getRootElement() == null);
    }
}
